<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="版本号" prop="version">-->
<!--        <el-input-->
<!--          v-model="queryParams.version"-->
<!--          placeholder="请输入版本号"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="内部版本号" prop="internalVersion">-->
<!--        <el-input-->
<!--          v-model="queryParams.internalVersion"-->
<!--          placeholder="请输入内部版本号"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品状态" prop="productStatus" style="width: 264.4px">
        <el-select v-model="queryParams.productStatus" placeholder="请选择产品状态" clearable>
          <el-option
            v-for="dict in scm_product_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['scm:scmProducts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['scm:scmProducts:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['scm:scmProducts:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['scm:scmProducts:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" showColumnsType="transfer" ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scmProductsList" @selection-change="handleSelectionChange" :scrollbar-always-on="true" :row-class-name="tableRowClassName" >
      <el-table-column type="selection" width="50" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" width="50" />-->
      <el-table-column label="图号" align="left" prop="drawingNumber" width="100" v-if="columns[0].visible" />
      <el-table-column label="版本" align="center" prop="version" width="50" v-if="columns[1].visible" />
      <el-table-column label="内版本" align="center" prop="internalVersion" width="65" v-if="columns[2].visible" />
      <el-table-column label="产品名称" align="left" prop="productName" width="150" v-if="columns[3].visible" />
      <el-table-column label="产品状态" align="center" prop="productStatus" width="85" v-if="columns[4].visible" >
        <template #default="scope">
          <dict-tag :options="scm_product_status" :value="scope.row.productStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="材质" align="center" prop="material" width="65" v-if="columns[5].visible" />
      <el-table-column label="阻燃等级" align="center" prop="inflamingRetardingLevel" width="80" v-if="columns[6].visible" />
      <el-table-column label="规格" align="center" prop="specification" width="50" v-if="columns[7].visible" />
      <el-table-column label="型号" align="center" prop="model" width="65" v-if="columns[8].visible" :show-overflow-tooltip="true" />
      <el-table-column label="颜色" align="center" prop="color" width="50" v-if="columns[9].visible" :show-overflow-tooltip="true" />
      <el-table-column label="图纸构成" align="center" prop="drawingComposition" width="80" v-if="columns[10].visible" />
      <el-table-column label="量产单位" align="center" prop="massUnit" width="80" v-if="columns[11].visible" />
      <el-table-column label="量产价格" align="center" prop="massUnitPrice" width="80" v-if="columns[12].visible" />
      <el-table-column label="图纸名字" align="center" prop="drawingAttachmentName" :show-overflow-tooltip="true" v-if="columns[13].visible" />
      <el-table-column label="图纸地址" align="center" prop="drawingAttachmentUrl" :show-overflow-tooltip="true" v-if="columns[14].visible" />
      <el-table-column label="产品备注" align="left" prop="productRemark" :show-overflow-tooltip="true" width="200" v-if="columns[15].visible" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmProducts:edit']">修正</el-button>
          <el-button link type="primary" icon="Sell" @click="handleUpgrade(scope.row)" v-hasPermi="['scm:scmProducts:edit']">升级</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmProducts:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="scmProductsRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="图号" prop="drawingNumber">
              <el-input v-model="form.drawingNumber" placeholder="请输入图号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="form.version" placeholder="请输入版本号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="内部版本" prop="internalVersion">
              <el-input v-model="form.internalVersion" placeholder="请输入内部版本号" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="品名" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品状态" prop="productStatus">
              <el-select v-model="form.productStatus" placeholder="请选择产品状态">
                <el-option
                    v-for="dict in scm_product_status"  :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="颜色" prop="color">
              <el-input v-model="form.color" placeholder="请输入颜色" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="材质" prop="material">
              <el-input v-model="form.material" placeholder="请输入材质" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="阻燃等级" prop="inflamingRetardingLevel">
              <el-input v-model="form.inflamingRetardingLevel" placeholder="请输入阻燃等级" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="图纸构成" prop="drawingComposition">
              <el-input v-model="form.drawingComposition" placeholder="请输入图纸构成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="量产单位" prop="massUnit">
              <el-input v-model="form.massUnit" placeholder="请输入量产单位" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="量产价格" prop="specification">
              <el-input v-model="form.massUnitPrice" placeholder="请输入量产价格" type="number">
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="24">
<!--          <el-col :span="12">-->
<!--            <el-form-item label="图纸名" prop="drawingAttachmentName">-->
<!--              <el-input v-model="form.drawingAttachmentName" placeholder="请输入上传图纸名字" style="flex: 1;" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="18">
            <el-form-item label="图纸" prop="drawingAttachmentUrl">
              <div style="display: flex; gap: 10px; align-items: center; width: 100%">
                <el-input :value="form.drawingAttachmentUrl ? form.drawingAttachmentUrl.substring(form.drawingAttachmentUrl.lastIndexOf('/') + 1) : '' " placeholder="请上传图纸" style="flex: 2;" disabled />
                <file-upload v-model="form.drawingAttachmentUrl" :isShowTip="false"/>
                <el-button size="default" type="text" @click="$download.resource(form.drawingAttachmentUrl,false)">下载</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="产品备注" prop="productRemark">
          <el-input v-model="form.productRemark" type="textarea" placeholder="请输入内容" :rows="3" />
        </el-form-item>

        <el-divider content-position="center">产品子图信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddScmProductsSub">添加子图</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" icon="Delete" @click="handleDeleteScmProductsSub">删除</el-button>-->
<!--          </el-col>-->
        </el-row>
        <el-table :data="scmProductsSubList" :row-class-name="rowScmProductsSubIndex" @selection-change="handleScmProductsSubSelectionChange" ref="scmProductsSub" :show-header="false">
<!--          <el-table-column type="selection" width="50" align="center" />-->
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="子图号" align="center"  width="80">子图号</el-table-column>
          <el-table-column label="子图号" prop="drawingSubNumber" >
            <template #default="scope">
              <el-input v-model="scope.row.drawingSubNumber" placeholder="请输入子图号" />
            </template>
          </el-table-column>
<!--          <el-table-column label="子图名" prop="drawingSubAttachmentName" width="150">-->
<!--            <template #default="scope">-->
<!--              <el-input v-model="scope.row.drawingSubAttachmentName" placeholder="请输入子图名" />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="附件地址" prop="drawingSubAttachmentUrl" >
            <template #default="scope">
              <el-input v-model="scope.row.drawingSubAttachmentUrl" placeholder="文件名字，上传后自动生成" :disabled="true"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="290">
            <template #default="scope">
              <div style="display: flex; gap: 10px; align-items: center; width: 100%">
                <file-upload v-model="scope.row.drawingSubAttachmentUrl" :isShowTip="false"/>
                <el-button size="default" type="text" icon="Download" @click="$download.resource(scope.row.drawingSubAttachmentUrl,false)">下载</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmProducts:remove']">删除</el-button>
              </div>
<!--              <el-button link type="primary" icon="Upload" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmProducts:edit']">上传</el-button>-->
<!--              <el-button link type="primary" icon="Download" @click="handleUpdate(scope.row)" v-hasPermi="['scm:scmProducts:edit']">下载</el-button>-->
<!--              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmProducts:remove']">删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ScmProducts">
import {
  addScmProducts,
  delScmProducts,
  getScmProducts,
  listScmProducts,
  updateScmProducts
} from "@/api/scm/scmProducts";

const { proxy } = getCurrentInstance();
const { scm_product_status } = proxy.useDict('scm_product_status');
const scmProductsList = ref([]);
const scmProductsSubList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedScmProductsSub = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drawingNumber: null,
    version: null,
    internalVersion: null,
    productName: null,
    productStatus: null,
  },
  rules: {
    drawingNumber: [
      { required: true, message: "图号不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询产品列表 */
function getList() {
  loading.value = true;
  // 清空颜色映射，重新分配
  drawingNumberColorMap.clear();
  colorCounter = 0;
  listScmProducts(queryParams.value).then(response => {
    scmProductsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    drawingNumber: null,
    version: null,
    internalVersion: null,
    productName: null,
    productStatus: null,
    material: null,
    inflamingRetardingLevel: null,
    specification: null,
    model: null,
    color: null,
    drawingComposition: null,
    drawingAttachmentName: null,
    drawingAttachmentUrl: '',
    productRemark: null,
    massUnit: null,
    massUnitPrice: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  scmProductsSubList.value = [];
  proxy.resetForm("scmProductsRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加产品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getScmProducts(_id).then(response => {
    form.value = response.data;
    scmProductsSubList.value = response.data.scmProductsSubList;
    open.value = true;
    title.value = "修改产品";
  });
}

/** 升级按钮操作 */
function handleUpgrade(row) {
  reset();
  const _id = row.id || ids.value
  getScmProducts(_id).then(response => {
    form.value = response.data;
    scmProductsSubList.value = response.data.scmProductsSubList;
    open.value = true;
    title.value = "修改产品";
    form.value.internalVersion++;
    form.value.parentId = form.value.id;
    form.value.id = null;
    scmProductsSubList.value.forEach(item => {
      if (item.productId) {
        item.productId = "";
        item.id = null;
      }
    });

  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scmProductsRef"].validate(valid => {
    if (valid) {
      form.value.scmProductsSubList = scmProductsSubList.value;
      form.value.drawingAttachmentName = form.value.drawingAttachmentUrl.substring(form.value.drawingAttachmentUrl.lastIndexOf('/') + 1)
      if (form.value.id != null) {
        updateScmProducts(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addScmProducts(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除产品编号为"' + _ids + '"的数据项？').then(function() {
    return delScmProducts(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 产品子表序号 */
function rowScmProductsSubIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 产品子表添加按钮操作 */
function handleAddScmProductsSub() {
  let obj = {};
  obj.drawingSubNumber = "";
  obj.drawingSubAttachmentName = "";
  obj.drawingSubAttachmentUrl = "";
  obj.productSubRemark = "";
  scmProductsSubList.value.push(obj);
}

/** 产品子表删除按钮操作 */
function handleDeleteScmProductsSub() {
  if (checkedScmProductsSub.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的产品子表数据");
  } else {
    const scmProductsSubs = scmProductsSubList.value;
    const checkedScmProductsSubs = checkedScmProductsSub.value;
    scmProductsSubList.value = scmProductsSubs.filter(function(item) {
      return checkedScmProductsSubs.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleScmProductsSubSelectionChange(selection) {
  checkedScmProductsSub.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('scm/scmProducts/export', {
    ...queryParams.value
  }, `产品信息_${new Date().getTime()}.xlsx`)
}


// 列显隐信息
const columns = ref([
  { key: 0, label: `图号`, visible: true },
  { key: 1, label: `版本`, visible: true },
  { key: 2, label: `内版本`, visible: true },
  { key: 3, label: `产品名称`, visible: true },
  { key: 4, label: `产品状态`, visible: true },
  { key: 5, label: `材质`, visible: true },
  { key: 6, label: `阻燃等级`, visible: true },
  { key: 7, label: `规则`, visible: true },
  { key: 8, label: `型号`, visible: true },
  { key: 9, label: `颜色`, visible: true },
  { key: 10, label: `图纸构成`, visible: true },
  { key: 11, label: `量产单位`, visible: true },
  { key: 12, label: `量产价格`, visible: true },
  { key: 13, label: `图纸名字`, visible: true },
  { key: 14, label: `图纸地址`, visible: true },
  { key: 15, label: `产品备注`, visible: true }
]);

// 添加颜色映射和计数器
const drawingNumberColorMap = new Map();
let colorCounter = 0;
const colorClasses = ['drawing-number-row-0', 'drawing-number-row-1'];

// 修改 tableRowClassName 函数
function tableRowClassName({ row, rowIndex }) {
  if (!row.drawingNumber) return '';

  // 检查是否已经为该 drawingNumber 分配了颜色
  if (drawingNumberColorMap.has(row.drawingNumber)) {
    return drawingNumberColorMap.get(row.drawingNumber);
  }

  // 为新的 drawingNumber 分配颜色
  const colorClass = colorClasses[colorCounter % colorClasses.length];
  drawingNumberColorMap.set(row.drawingNumber, colorClass);
  colorCounter++;

  return colorClass;
}

getList();
</script>


<style >/* 定义10种不同的背景色 */
.el-table .drawing-number-row-0 {
  background: #e8f5e8;
}

.el-table .drawing-number-row-1 {
  background: #e8e8f5;
}

.el-table .drawing-number-row-2 {
  background: #fff0f0;
}

.el-table .drawing-number-row-3 {
  background-color: #f0fff0;
}

.el-table .drawing-number-row-4 {
  background-color: #fff0ff;
}

.el-table .drawing-number-row-5 {
  background-color: #f0fdff;
}

.el-table .drawing-number-row-6 {
  background-color: #fff8f0;
}

.el-table .drawing-number-row-7 {
  background-color: #f8f0ff;
}

.el-table .drawing-number-row-8 {
  background-color: #f0f8ff;
}

.el-table .drawing-number-row-9 {
  background-color: #f5f5f5;
}
</style>